﻿using System.Text;
using Asp.Versioning;
using Asp.Versioning.ApiExplorer;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace WebApi.ConfigureOptions;

public class ConfigureSwaggerOptions(
    IApiVersionDescriptionProvider provider
) : IConfigureOptions<SwaggerGenOptions>
{
    /// <summary>
    /// Configures the Swagger options.
    /// </summary>
    /// <param name="options"></param>
    public void Configure(SwaggerGenOptions options)
    {
        foreach (ApiVersionDescription description in provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(description.GroupName, CreateOpenApiInfo(description));
        }
    }
    private static OpenApiInfo CreateOpenApiInfo(ApiVersionDescription description)
    {
        var text = new StringBuilder("An application with OpenAPI, Swashbuckle, and API versioning.");
        var info = new OpenApiInfo
        {
            Title = "Api Versioning Example",
            Version = description.ApiVersion.ToString(),
        };
        if (description.IsDeprecated)
        {
            text.Append("This API version has been deprecated.");
        }
        if (description.SunsetPolicy is { } policy)
        {
            if (policy.Date is { } when)
            {
                text.Append("The API will be sunset on ")
                    .Append(when.Date.ToShortDateString())
                    .Append('.');
            }
            if (policy.HasLinks)
            {
                text.AppendLine();
                foreach (LinkHeaderValue link in policy.Links)
                {
                    if (link.Type == "text/html")
                    {
                        text.AppendLine();
                        if (link.Title.HasValue)
                        {
                            text.Append(link.Title.Value).Append(": ");
                        }
                        text.Append(link.LinkTarget.OriginalString);
                    }
                }
            }
        }
        info.Description = text.ToString();
        return info;
    }
}
